package com.example.fish.service.impl;

import com.example.fish.mapper.EventMapper;
import com.example.fish.mapper.SignMapper;
import com.example.fish.mapper.UserInfoMapper;
import com.example.fish.pojo.*;
import com.example.fish.service.EventService;
import com.example.fish.service.ex.*;
import com.example.fish.vo.EventDetail;
import com.example.fish.vo.EventOther;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class EventServiceImpl implements EventService {
    @Autowired
    private EventMapper eventMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SignMapper signMapper;

    /***
     * 根据publish time 来 排序，分页查询所有的eventDetails
     * @return  page info
     */
    @Override
    public PageInfo<EventDetail> getAll(Integer pageNum) {
        Integer pageSize = 10 ;
        EventExample example = new EventExample();
        example.setOrderByClause("state DESC,publishtime DESC");
        int i = eventMapper.countByExample(null);
        PageHelper.startPage(pageNum,pageSize);
        List<Event> events = eventMapper.selectByExample(example);
        List<EventDetail> list = new ArrayList<>();

//        封装EventDetail用于返回pageInfo
        for (Event event : events) {
            EventDetail detail = new EventDetail();
            detail.setEvent(event);
//            查询发布者的信息
            UserInfo user = userInfoMapper.selectByPrimaryKey(event.getUserid());
            detail.setUsername(user.getName());
            detail.setAvatar(user.getAvator());
            detail.setFishage(user.getFishage());
            list.add(detail);
        }
        PageInfo<EventDetail> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(i);
        return pageInfo;
    }

    /***
     * 根据eventid查询单个event
     */
    @Override
    public Event getById(Integer eventid) {
        Event event = eventMapper.selectByPrimaryKey(eventid);
        if (event == null){
            throw new EventNotFoundException("活动不存在");
        }
        return event;
    }

    /***
     * 还未开始的活动
     * @return pageInfo
     */
    @Override
    public PageInfo<EventDetail> getNotStart(Integer pageNum) {
        Integer pageSize = 10;
        EventExample example = new EventExample();
        example.createCriteria().andStateEqualTo("未开始");
        example.setOrderByClause("publishtime DESC");
        int i = eventMapper.countByExample(example);
        PageHelper.startPage(pageNum,pageSize);
        List<Event> events = eventMapper.selectByExample(example);
        List<EventDetail> list = new ArrayList<>();
        for (Event event : events) {
//            封装对象
            EventDetail detail = new EventDetail();
            detail.setEvent(event);
//            查询发布者的信息
            UserInfo user = userInfoMapper.selectByPrimaryKey(event.getUserid());
            detail.setUsername(user.getName());
            detail.setAvatar(user.getAvator());
            detail.setFishage(user.getFishage());
            list.add(detail);
        }
        PageInfo<EventDetail> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(i);
        return pageInfo;
    }

    /***
     * 根据活动状态查询   未开始/已结束
     */
    @Override
    public PageInfo<EventDetail> findByState(Integer pageNum,String state) {
        Integer pageSize = 10;
        EventExample example = new EventExample();
        example.createCriteria().andStateEqualTo(state);
        example.setOrderByClause("publishtime DESC");
        int i = eventMapper.countByExample(example);
        PageHelper.startPage(pageNum,pageSize);
        List<Event> events = eventMapper.selectByExample(example);
        List<EventDetail> list = new ArrayList<>();
        for (Event event : events) {
//            封装对象
            EventDetail detail = new EventDetail();
            detail.setEvent(event);
//            查询发布者的信息
            UserInfo user = userInfoMapper.selectByPrimaryKey(event.getUserid());
            detail.setUsername(user.getName());
            detail.setAvatar(user.getAvator());
            detail.setFishage(user.getFishage());
            list.add(detail);
        }
        PageInfo<EventDetail> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(i);
        return pageInfo;
    }

    /***
     * 我发起的/我参与的 --- 根据id查询
     * @param userId 用户id
     * @param flag  判断查询类型
     * @return  pageInfo
     */
    @Override
    public PageInfo<EventOther> findByUserId(Integer pageNum, Integer userId, String flag) {
        Integer pageSize = 5;
//        判断
        if (flag.equals("1")){
//            查询我发起的event
            EventExample example = new EventExample();
            example.setOrderByClause("state DESC");
            example.createCriteria().andUseridEqualTo(userId);
            int i = eventMapper.countByExample(example);
//            PageHelper.startPage(pageNum,pageSize);
            PageHelper.startPage(pageNum,pageSize);
            List<Event> events = eventMapper.selectByExample(example);
            List<EventOther> list = new ArrayList<>();
            for (Event event : events) {
//                封装对象
                EventOther eventOther = new EventOther();
                eventOther.setEventid(event.getEventid());
                eventOther.setType(event.getType());
                eventOther.setTime(event.getPublishtime());
                eventOther.setTitle(event.getTitle());
                eventOther.setUserid(event.getUserid());
                eventOther.setState(event.getState());
                list.add(eventOther);
            }
            PageInfo<EventOther> pageInfo = new PageInfo<>(list);
            pageInfo.setTotal(i);
            pageInfo.setPageNum(pageNum);
            pageInfo.setPageSize(pageSize);
            return pageInfo;
        }else {
//            查询我参与的
//            先查询总条数
            SignExample signExample = new SignExample();
            signExample.createCriteria().andUseridEqualTo(userId);
            int i = signMapper.countByExample(signExample);
            PageHelper.startPage(pageNum,pageSize);
            List<Sign> signs = signMapper.selectByExample(signExample);
            List<EventOther> list = new ArrayList<>();
            for (Sign sign : signs) {
                Event event = eventMapper.selectByPrimaryKey(sign.getEventid());
                if(event == null){
                    continue;
                }
                EventOther eventOther = new EventOther();
                eventOther.setEventid(sign.getEventid());
                eventOther.setType(event.getType());
                eventOther.setTime(sign.getSigntime());
                eventOther.setTitle(event.getTitle());
                eventOther.setUserid(event.getUserid());
                eventOther.setState(event.getState());
                list.add(eventOther);
            }
//            对list中eventOther 的 state 进行排序操作
            Collections.sort(list, new Comparator<EventOther>() {
                @Override
                public int compare(EventOther o1, EventOther o2) {
                    return o2.getState().compareTo(o1.getState());
                }
            });
            PageInfo<EventOther> pageInfo = new PageInfo<>(list);
            pageInfo.setTotal(i);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPageNum(pageNum);
            return pageInfo;
        }
    }

    @Override
    public void deleteByEventId(Integer eventid) {
        int i = eventMapper.deleteByPrimaryKey(eventid);
        if (i == 0){
            throw new EventException("删除失败");
        }
    }

    /***
     * 报名操作
     * @param userid
     * @param eventid
     */
    @Override
    public void signIn(Integer userid, Integer eventid) {
//        先查询到event  判断报名人数是不是满了
        Event event = eventMapper.selectByPrimaryKey(eventid);
        Integer size = event.getSize();
        Integer signed = event.getSigned();
        if (signed >= size){
            throw new EventSignException("报名人数已满");
        }
//        再查询是不是报过名
        SignExample example = new SignExample();
        example.createCriteria().andEventidEqualTo(eventid).andUseridEqualTo(userid);
        List<Sign> signs = signMapper.selectByExample(example);
        if (signs.size() > 0){
            throw new EventAlreadySignedException("已经报过名了");
        }
//        存储报名信息
//        event 的signed +1
        event.setSigned(event.getSigned()+1);
        eventMapper.updateByPrimaryKey(event);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = now.format(formatter);
        Sign sign = new Sign();
        sign.setEventid(eventid);
        sign.setUserid(userid);
        sign.setSigntime(time);
        signMapper.insert(sign);
    }

    @Override
    public Boolean IsSigned(Integer userid, Integer eventid) {
        SignExample signExample = new SignExample();
        signExample.createCriteria().andUseridEqualTo(userid).andEventidEqualTo(eventid);
        int i = signMapper.countByExample(signExample);
        if (i == 0){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void signOut(Integer userid, Integer eventid) {
//        根据userid和event id 查询到对应的sign记录，，删除该记录
        SignExample example = new SignExample();
        example.createCriteria().andEventidEqualTo(eventid).andUseridEqualTo(userid);
        int i = signMapper.deleteByExample(example);
        if (i == 0){
            throw new SignDoNotExistException("报名记录不存在");
        }
    }

    /***
     * 根据event id 将state改成 已取消
     */
    @Override
    public void cancelEvent(Integer eventid) {
        Event event = eventMapper.selectByPrimaryKey(eventid);
        event.setState("已取消");
        eventMapper.updateByPrimaryKey(event);
    }

    @Override
    public void holdEvent(Integer userid, Event event) {
        event.setState("未开始");
        event.setSigned(0);
        event.setUserid(userid);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 创建日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化日期
        String formattedDate = currentDate.format(formatter);
        event.setPublishtime(formattedDate);
        eventMapper.insert(event);
    }
}
